<template>
  <div class="app-container text2ssml">
    <ContentLayout>
      <SsmlTools
        :selectConfig="selectConfig"
        :inputHtml="inputHtml"
        @handleFocus="handleFocus"
      ></SsmlTools
      >lǚ bù
      <div
        class="ssml-editor"
        ref="inputRef"
        :class="{ 'is-default': !inputHtml && !isFocus }"
        contenteditable="true"
        @focus="handleFocus"
        @input="handleInput"
        @blur="handleBlur"
        v-html="inputContent"
      ></div>
    </ContentLayout>
  </div>
</template>

<script setup lang="ts">
import { pinyin, polyphonic } from "pinyin-pro";
import { getSelection } from "@/utils/selectionRang";
onMounted(() => {
  console.log(pinyin("吕布 原密碼錯誤 購買商品獲得積分", { v: true }));

  document.addEventListener("click", handleDocumentClick);
  document.addEventListener("selectionchange", handleSelectionChange);
});
onBeforeUnmount(() => {
  document.removeEventListener("click", handleDocumentClick);
});
const selectedText = ref("");
const isFocus = ref<boolean>(false);
const defaultPlaceholder = "请输入内容...";
const inputRef = ref<HTMLInputElement>();
const selectConfig = ref({});
const inputHtml = ref(``);
const inputContent = computed(() => {
  return inputHtml.value
    ? inputHtml.value
    : isFocus.value
    ? ""
    : defaultPlaceholder;
});
function handleSelectionChange() {
  const selection = getSelection(inputRef.value);
  if (!selection || !inputRef.value) {
    selectedText.value = "";
    return;
  }
  selectedText.value = selection.toString();
  // console.log("当前选中文本:", selectedText.value);
  // 获取选中范围的HTML
  const range = selection.getRangeAt(0);
  const fragment = range.cloneContents();
  const tempDiv = document.createElement("div");
  tempDiv.appendChild(fragment);
}

function handleFocus(e: any) {
  isFocus.value = true;
  inputRef.value?.focus();
}
function handleInput(e: any) {
  const inputHTML = e.target.innerHTML;
  // 检测是否为空（仅包含 <br> 或 &nbsp;）
  if (inputHTML === "<br>" || inputHTML === "&nbsp;") {
    e.target.innerHTML = ""; // 强制清空
    inputHtml.value = "";
  } else {
    inputHtml.value = inputHTML;
  }
}

const handleDocumentClick = (e: MouseEvent) => {
  const target = e.target as HTMLElement;
  const clickedToolItem = target.closest(".ssml-tools .stop-time"); // 修改为捕获整个 li 区域
  const clickedInside = target.closest(".ssml-editor");
  if (isFocus.value) {
    if (!clickedToolItem && !clickedInside) {
      isFocus.value = false;
      inputRef.value?.blur();
    }
  }
};
// 获取焦点及其位置等相关信息
function handleBlur() {
  const sel = getSelection(inputRef.value);
  if (!sel || sel.rangeCount === 0) return;

  const range = sel.getRangeAt(0);
  selectConfig.value = {
    position: range.startOffset,
    element: range.startContainer,
    // 保存更多上下文信息
    textContent: range.startContainer.textContent,
  };
}
</script>

<style lang="scss" scoped>
.text2ssml {
  .ssml-editor {
    margin-top: 20px;
    height: 200px;
    border: 1px solid $color_1;
    padding: 12px;
    border-radius: 8px;
    font-size: 14px;
  }
  .is-default {
    color: $color_a;
  }
}
</style>
<style lang="scss">
.ssml-editor {
  s {
    text-decoration: none;
  }
}
</style>
